package jgcp.common.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
 * 
 * @Date 28/05/2009
 * @author Jie Zhao (288654)
 * @version 1.0
 */
public class Connection implements Comparable<Connection>{
	public int compareTo(Connection o) {
		return this.id - o.getId();
	}
	private int id = 0;
	private String address ="";
	private int port = 0;
	private String name = "";
	private Socket socket = null;

	/**
	 * @return the socket
	 */
	public Socket getSocket() {
		return socket;
	}
	/**
	 * @param socket the socket to set
	 */
	public void setSocket(Socket socket) {
		this.socket = socket;
		this.address = socket.getInetAddress().getHostAddress();
	}
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("Connection: [ID=");
		sb.append(id);
		sb.append(", name=");
		sb.append(name);
		sb.append(",Address=");
		sb.append(address);
		sb.append(":");
		sb.append(port);
		sb.append("]");
		return sb.toString();
	}
	/**
	 * @return the workerName
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param workerName the workerName to set
	 */
	public void setName(String workerName) {
		this.name = workerName;
	}

	/**
	 * @return the workerAddress
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param workerAddress the workerAddress to set
	 */
	public void setAddress(String workerAddress) {
		this.address = workerAddress;
	}

	/**
	 * @return the communicationPort
	 */
	public int getPort() {
		return port;
	}

	/**
	 * @param communicationPort the communicationPort to set
	 */
	public void setPort(int communicationPort) {
		this.port = communicationPort;
	}

	public int getId() {
		return id;
	}

	public void setId(int workerId) {
		this.id = workerId;
	}
	public void writeData(byte[] data) throws Exception
	{
		if(socket.isClosed() || socket.isOutputShutdown())return;
		OutputStream os = socket.getOutputStream();
		os.write(data);
		os.flush();
	}
	public byte[] readData() throws IOException
	{
		if(socket.isClosed() || socket.isInputShutdown())return null;
		byte[] buffer = new byte[65535];
		InputStream is = socket.getInputStream();
		int length = is.read(buffer);
		if(length == -1)
		{
			return null;
		}
		else
		{
			byte[] result = new byte[length];
			for(int i=0;i<length;i++)
			{
				result[i] = buffer[i];
			}
			buffer = null;
			return result;
		}
	}
}
